package com.fq.ifs.servlet;

import com.google.common.base.Strings;
import com.google.common.io.ByteStreams;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FSDataOutputStream;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URLEncoder;

@MultipartConfig
@WebServlet(name = "ImageFileUploadServlet", urlPatterns = "/upload.action", asyncSupported = true)
public class ImageFileUploadServlet extends HttpServlet {

    private static final String SAVE_FILE_NAME = "hdfs://139.129.9.166/ifs/%s";

    private static final String HYPERTEXT_LINK = "http://139.129.9.166:8080/IFS/download.action?filename=%s";

    private static final String USER = "root";

    // private static final int _4M_BUFFER = 1024 * 1024 * 4;

    @Override
    protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        Part file = request.getPart("file");
        String fileName = getFileName(file);
        if (isFileValid(file, fileName)) {
            String destFileName = generateDestFileName(fileName);

            // 保存文件到HDFS
            FileSystem fs;
            try {
                fs = FileSystem.get(URI.create(destFileName), new Configuration(), USER);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }

            try (FSDataOutputStream out = fs.create(new Path(destFileName), true);
                 InputStream in = file.getInputStream()
            ) {
                ByteStreams.copy(in, out);
            }

            // 生成外链
            String link = String.format(HYPERTEXT_LINK, fileName);
            writer.print(String.format("外链: <a href=%s>%s</a><hr/>", link, link));
        } else {
            writer.print("Error : Image Type Error");
        }
    }

    /**
     * 校验文件表单域有效
     *
     * @param file
     * @param fileName
     * @return
     */
    private boolean isFileValid(Part file, String fileName) {
        // 上传的并非文件
        if (file.getContentType() == null) {
            return false;
        }
        // 没有选择任何文件
        else if (Strings.isNullOrEmpty(fileName)) {
            return false;
        }

        return true;
    }


    private String generateDestFileName(String fileName) {
        try {
            return String.format(SAVE_FILE_NAME, URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }

    private String getFileName(Part part) {
        String[] elements = part.getHeader("content-disposition").split(";");
        for (String element : elements) {
            if (element.trim().startsWith("filename")) {
                return element.substring(element.indexOf("=") + 1).trim().replace("\"", "");
            }
        }
        return null;
    }
}